package com.poizon.infrastructure.idem.core.domain;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.poizon.infrastructure.idem.core.domain.entity.IdemEntity;
import com.poizon.infrastructure.idem.core.domain.value.config.IdemConstants;
import com.poizon.infrastructure.idem.core.repo.IIdemDbStoreRepo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;

import java.util.Map;
import java.util.Optional;


/**
 * 充血模型/仓储初始化
 */
@Slf4j
public class IdemDomainInit implements ApplicationRunner {

    public static final String err_msg = "[通用幂等框架] 未定义幂等存储实现";

    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.info("[通用幂等框架] 准备初始化默认幂等存储实现");

        try {
            Map<String, IIdemDbStoreRepo> beansOfType = SpringUtil.getBeansOfType(IIdemDbStoreRepo.class);
            Assert.notNull(beansOfType, err_msg);
            Assert.notEmpty(beansOfType.entrySet(), err_msg);
            Assert.notEmpty(beansOfType.values(), err_msg);
            IIdemDbStoreRepo iIdemDbStoreRepo = Optional.ofNullable(beansOfType.get(IdemConstants.IDEM_DB_STORE_TYPE)).orElse(beansOfType.values().stream().limit(1).findAny().get());
            ReflectUtil.setFieldValue(IdemEntity.class, "iIdemDbStoreRepo", iIdemDbStoreRepo);
            log.info("[通用幂等框架] 成功初始化幂等存储默认实现={}", iIdemDbStoreRepo);
        } catch (Exception e) {
            log.error(StrUtil.format("[通用幂等框架] 无法获取到幂等存储实现,请检查相关配置是否正确"), e);
        }
    }
}
